//
//  BookingViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/7/14.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class BookingViewController: UIViewController {

    var scrollView: UIScrollView?
    
    let authManager = AuthManager.share
    
    let userAuthVM = UserAuthViewModel.shared
    
    var restaurant: RestaurantDetailResponse?
    
    var chosenBH: RestaurantBanquetHall?
    
    var orderVM: OrderViewModel?
    
    let disposeBag = DisposeBag()
    
    var notResign: Bool = false
    
    var toWaitSec: Int = 0
    
    var timer: Timer = Timer()
    
    let nameLabel: UILabel = {
        let label = UILabel()
        label.font = moreFont(size: 19)
        label.numberOfLines = 0
        label.textColor = UIColor.black
        return label
    }()
    
    let discountMessage: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 12)
        label.textColor = UIColor.lightGray
        label.numberOfLines = 0
        return label
    }()
    
    let saperator: UIView = {
        let view = UIView()
        return view
    }()
    
    let descriptionLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 12)
        label.numberOfLines = 0
        label.textColor = UIColor.gray
        return label
    }()
    
    let banquetHallField: UILabel = {
        let label = UILabel()
        label.text = LanguageHelper.getString(key: "NOT_YET_CHOOSE")
        label.font = AppFont(size: 14)
        label.textColor = UIColor.lightGray
        return label
    }()
    
    let quantityField: UITextField = {
        let textfield = UITextField()
        textfield.placeholder = LanguageHelper.getString(key: "FEAST_TABLE")
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        textfield.keyboardType = .numberPad
        return textfield
    }()
    
    let refereeField: UITextField = {
        let textfield = UITextField()
        textfield.placeholder = LanguageHelper.getString(key: "RECOMMENDER")
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        return textfield
    }()
    
    let contactManField: UITextField = {
        let textfield = UITextField()
        textfield.placeholder = LanguageHelper.getString(key: "CONTACTMAN")
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        return textfield
    }()
    
    let contactField: UITextField = {
        let textfield = UITextField()
        textfield.placeholder = LanguageHelper.getString(key: "PHONE")
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        textfield.keyboardType = .numberPad
        return textfield
    }()
    
    let verifyCodeField: UITextField = {
        let textfield = UITextField()
        textfield.placeholder = LanguageHelper.getString(key: "VERIFYCODE")
        textfield.font = AppFont(size: 14)
        textfield.tintColor = UIColor.black
        textfield.textColor = UIColor.gray
        textfield.keyboardType = .numberPad
        return textfield
    }()
    
    let getVerifyButton: UIButton = {
        let button = UIButton()
        button.layer.borderColor = UIColor.lightGray.cgColor
        button.backgroundColor = lightSaperatorColor
        button.layer.borderWidth = 1
        button.layer.cornerRadius = 3
        button.setTitle(LanguageHelper.getString(key: "GET_VERIFY_CODE"), for: .normal)
        button.setTitleColor(UIColor.gray, for: .normal)
        button.titleLabel?.font = AppFont(size: 13)
        return button
    }()
    
    @IBOutlet weak var button: UIButton!
    
    let dateArea: DateArea = DateArea()
    
    var textFields: [UITextField] = []
    
    var tapGestures: [UITapGestureRecognizer] = []
    
    var isBH: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = restaurant?.name
        
        button.layer.cornerRadius = 3
        button.layer.masksToBounds = true
        
        setBackBarItem()

        scrollView = UIScrollView()
        scrollView?.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height - 55)
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.isScrollEnabled = true
        scrollView?.autoresizingMask = UIViewAutoresizing.flexibleHeight
        scrollView?.backgroundColor = lightSaperatorColor
        scrollView?.alwaysBounceVertical = true
        scrollView?.delegate = self
        
        let banquetHallView = UIView()
        banquetHallView.backgroundColor = UIColor.white
        banquetHallView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: menuHeight)
        let bhtitleLabel = UILabel()
        bhtitleLabel.font = AppFont(size: 14)
        bhtitleLabel.textColor = UIColor.black
        bhtitleLabel.text = LanguageHelper.getString(key: "FEAST_HALL")
        let maxSize = CGSize(width: self.view.bounds.width, height: 30)
        let bhtitleWidth = TextSize.textSize(text: bhtitleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        bhtitleLabel.frame = UIEdgeInsetsInsetRect(banquetHallView.bounds, UIEdgeInsetsMake(10, 10, 10, banquetHallView.bounds.width - bhtitleWidth - 10))
        banquetHallField.frame = UIEdgeInsetsInsetRect(banquetHallView.bounds, UIEdgeInsetsMake(10, banquetHallView.bounds.width - 100 - 10, 10, 10))
        if isBH {
            if let bh = chosenBH {
                banquetHallField.text = bh.name
                banquetHallField.textColor = UIColor.gray
            }
        }
        let bhSaperator = UIView()
        bhSaperator.backgroundColor = lightSaperatorColor
        bhSaperator.frame = UIEdgeInsetsInsetRect(banquetHallView.bounds, UIEdgeInsetsMake(banquetHallView.bounds.height - 0.5, 0, 0, 0))
        
        let tapGesture = UITapGestureRecognizer()
        tapGesture.addTarget(self, action: #selector(chooseBanquetHall(_:)))
        banquetHallView.addGestureRecognizer(tapGesture)
        
        banquetHallView.addSubview(banquetHallField)
        banquetHallView.addSubview(bhtitleLabel)
        banquetHallView.addSubview(bhSaperator)
        scrollView?.addSubview(banquetHallView)
        
        let quantityView = UIView()
        quantityView.backgroundColor = UIColor.white
        quantityView.frame = CGRect(x: 0, y: menuHeight, width: self.view.bounds.width, height: menuHeight)
        let titleLabel = UILabel()
        titleLabel.font = AppFont(size: 14)
        titleLabel.textColor = UIColor.black
        titleLabel.text = LanguageHelper.getString(key: "QUANTITY")
        let titleWidth = TextSize.textSize(text: titleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        titleLabel.frame = UIEdgeInsetsInsetRect(quantityView.bounds, UIEdgeInsetsMake(10, 10, 10, quantityView.bounds.width - titleWidth - 10))
        quantityField.frame = UIEdgeInsetsInsetRect(quantityView.bounds, UIEdgeInsetsMake(10, quantityView.bounds.width - 100 - 10, 10, 10))
        let quantitySaperator = UIView()
        quantitySaperator.backgroundColor = lightSaperatorColor
        quantitySaperator.frame = UIEdgeInsetsInsetRect(quantityView.bounds, UIEdgeInsetsMake(quantityView.bounds.height - 0.5, 0, 0, 0))
        quantityView.addSubview(quantityField)
        quantityView.addSubview(titleLabel)
        quantityView.addSubview(quantitySaperator)
        scrollView?.addSubview(quantityView)
        
        let refereeView = UIView()
        refereeView.backgroundColor = UIColor.white
        refereeView.frame = CGRect(x: 0, y: menuHeight * 2, width: self.view.bounds.width, height: menuHeight)
        let reTitleLabel = UILabel()
        reTitleLabel.font = AppFont(size: 14)
        reTitleLabel.textColor = UIColor.black
        reTitleLabel.text = LanguageHelper.getString(key: "RECOMMENDER")
        let reTitleWidth = TextSize.textSize(text: reTitleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        reTitleLabel.frame = UIEdgeInsetsInsetRect(refereeView.bounds, UIEdgeInsetsMake(10, 10, 10, refereeView.bounds.width - reTitleWidth - 10))
        refereeField.frame = UIEdgeInsetsInsetRect(refereeView.bounds, UIEdgeInsetsMake(10, refereeView.bounds.width - 100 - 10, 10, 10))
        let refereeSaperator = UIView()
        refereeSaperator.backgroundColor = lightSaperatorColor
        refereeSaperator.frame = UIEdgeInsetsInsetRect(refereeView.bounds, UIEdgeInsetsMake(refereeView.bounds.height - 0.5, 0, 0, 0))
        refereeView.addSubview(refereeField)
        refereeView.addSubview(reTitleLabel)
        refereeView.addSubview(refereeSaperator)
        scrollView?.addSubview(refereeView)
        
        let contactmanView = UIView()
        contactmanView.backgroundColor = UIColor.white
        contactmanView.frame = CGRect(x: 0, y: menuHeight * 3, width: self.view.bounds.width, height: menuHeight)
        let cmtitleLabel = UILabel()
        cmtitleLabel.font = AppFont(size: 14)
        cmtitleLabel.textColor = UIColor.black
        cmtitleLabel.text = LanguageHelper.getString(key: "CONTACTMAN")
        let cmWidth = TextSize.textSize(text: cmtitleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        cmtitleLabel.frame = UIEdgeInsetsInsetRect(contactmanView.bounds, UIEdgeInsetsMake(10, 10, 10, contactmanView.bounds.width - cmWidth - 10))
        contactManField.frame = UIEdgeInsetsInsetRect(contactmanView.bounds, UIEdgeInsetsMake(10, contactmanView.bounds.width - 100 - 10, 10, 10))
        let cmSaperator = UIView()
        cmSaperator.backgroundColor = lightSaperatorColor
        cmSaperator.frame = UIEdgeInsetsInsetRect(contactmanView.bounds, UIEdgeInsetsMake(contactmanView.bounds.height - 0.5, 0, 0, 0))
        contactmanView.addSubview(contactManField)
        contactmanView.addSubview(cmtitleLabel)
        contactmanView.addSubview(cmSaperator)
        scrollView?.addSubview(contactmanView)
        
        let contactView = UIView()
        contactView.backgroundColor = UIColor.white
        contactView.frame = CGRect(x: 0, y: menuHeight * 4, width: self.view.bounds.width, height: menuHeight)
        let ctitleLabel = UILabel()
        ctitleLabel.font = AppFont(size: 14)
        ctitleLabel.textColor = UIColor.black
        ctitleLabel.text = LanguageHelper.getString(key: "PHONE")
        let cWidth = TextSize.textSize(text: ctitleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        ctitleLabel.frame = UIEdgeInsetsInsetRect(contactView.bounds, UIEdgeInsetsMake(10, 10, 10, contactView.bounds.width - cWidth - 10))
        contactField.frame = UIEdgeInsetsInsetRect(contactView.bounds, UIEdgeInsetsMake(10, contactView.bounds.width - 100 - 10, 10, 10))
        let cSaperator = UIView()
        cSaperator.backgroundColor = lightSaperatorColor
        cSaperator.frame = UIEdgeInsetsInsetRect(contactView.bounds, UIEdgeInsetsMake(contactView.bounds.height - 0.5, 0, 0, 0))
        contactView.addSubview(contactField)
        contactView.addSubview(ctitleLabel)
        contactView.addSubview(cSaperator)
        scrollView?.addSubview(contactView)
        
        let verifyView = UIView()
        verifyView.backgroundColor = UIColor.white
        verifyView.frame = CGRect(x: 0, y: menuHeight * 5, width: self.view.bounds.width, height: menuHeight)
        let vtitleLabel = UILabel()
        vtitleLabel.font = AppFont(size: 14)
        vtitleLabel.textColor = UIColor.black
        vtitleLabel.text = LanguageHelper.getString(key: "VERIFYCODE")
        let vWidth = TextSize.textSize(text: vtitleLabel.text!, font: moreFont(size: 14), maxSize: maxSize).width
        vtitleLabel.frame = UIEdgeInsetsInsetRect(verifyView.bounds, UIEdgeInsetsMake(10, 10, 10, verifyView.bounds.width - vWidth - 10))
        verifyCodeField.frame = UIEdgeInsetsInsetRect(verifyView.bounds, UIEdgeInsetsMake(10, verifyView.bounds.width - 200 - 10, 10, 100))
        getVerifyButton.frame = UIEdgeInsetsInsetRect(verifyView.bounds, UIEdgeInsetsMake(10, verifyView.bounds.width - 100 - 10, 10, 10))
        let vSaperator = UIView()
        vSaperator.backgroundColor = lightSaperatorColor
        vSaperator.frame = UIEdgeInsetsInsetRect(contactView.bounds, UIEdgeInsetsMake(verifyView.bounds.height - 0.5, 0, 0, 0))
        verifyView.addSubview(verifyCodeField)
        verifyView.addSubview(getVerifyButton)
        verifyView.addSubview(vtitleLabel)
        verifyView.addSubview(vSaperator)
        scrollView?.addSubview(verifyView)
        
        getVerifyButton.addTarget(self, action: #selector(getVerifyCode(_:)), for: .touchUpInside)
        
        textFields += [quantityField, refereeField, contactManField, contactField, verifyCodeField]
        for textfield in textFields {
            textfield.delegate = self
        }
        
        dateArea.frame = CGRect(x: 0, y: menuHeight * 6, width: self.view.bounds.width, height: menuHeight)
        dateArea.layoutSubviews()
        dateArea.delegate = self
        
        scrollView?.addSubview(dateArea)
        
        scrollView?.contentSize = CGSize(width: self.view.bounds.width, height: dateArea.frame.origin.y + dateArea.frame.height)
        
        self.view.addSubview(scrollView!)
        
        initVM()
    }
    
    func getVerifyCode(_ sender: UIButton) {
        if let token = authManager.getToken() as? String {
            userAuthVM.getTotp(token: token).subscribe(onNext: { [unowned self] response in                
                print(response)
                self.showPromptView(message: LanguageHelper.getString(key: "SENT"), confirmText: LanguageHelper.getString(key: "OK"))
            })
            .addDisposableTo(disposeBag)
            //冷却按钮
            self.toWaitSec = 60
            self.getVerifyButton.setTitle("\(LanguageHelper.getString(key: "RESENT"))（\(self.toWaitSec)）", for: .disabled)
            self.getVerifyButton.isEnabled = false
            timer = Foundation.Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(waitToGetAgain), userInfo: nil, repeats: true)
        }
    }
    
    func waitToGetAgain() {
        self.toWaitSec -= 1
        if self.toWaitSec == 0 {
            timer.invalidate()
            self.getVerifyButton.isEnabled = true
        } else {
            self.getVerifyButton.setTitle("\(LanguageHelper.getString(key: "RESENT"))（\(self.toWaitSec)）", for: .disabled)
        }
    }
    
    func initVM() {
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                orderVM = OrderViewModel(token: token)
            }
        }
    }
    
    func chooseDate(_ sender: UITapGestureRecognizer) {
        let tf = sender.view as! DateArea
        print(tf.frame)        
    }
    
    @IBAction func nextStep(_ sender: UIButton) {
        if chosenBH == nil || quantityField.text! == "" || contactField.text! == "" || contactManField.text! == "" || verifyCodeField.text! == "" {
            self.showPromptView(message: LanguageHelper.getString(key: "INCOMPLETE_INFO"), confirmText: LanguageHelper.getString(key: "OK"))
            return
        }
        if let quantity = quantityField.text {
            let q = Int(quantity)!
            if q < (chosenBH?.tableRange![0])! || q > (chosenBH?.tableRange![1])! {
                self.showPromptView(message: LanguageHelper.getString(key: "INVALID_QUANTITY"), confirmText: LanguageHelper.getString(key: "OK"))
                return
            }
        }
        var hasPickedADate = false
        for tfs in dateArea.textfields {
            if tfs.text != "" {
                hasPickedADate = true
                break
            }
        }
        if !hasPickedADate {
            self.showPromptView(message: LanguageHelper.getString(key: "AT_LEAST1DATE"), confirmText: LanguageHelper.getString(key: "OK"))
            return
        }
        var dateString = ""
        var isFirstDate = true
        for tfs in dateArea.textfields {
            if tfs.text != "" {
                if !isFirstDate {
                    dateString += ";"
                }
                dateString += tfs.text!
                isFirstDate = false
            }
        }
        
        let orderPost = OrderPost(banquetHallId: (chosenBH?.id)!, candidateDates: dateString, contact: contactManField.text!, phone: contactField.text!, recommender: refereeField.text!, tables: Int(quantityField.text!)!, totp: verifyCodeField.text!)
        
        if let vm = orderVM {
            vm.postOrder(order: orderPost).subscribe(onNext: { response in
                if let status = response.status {                    
                    if status != 200 {
                        self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
                    } else {
                        self.showPromptView(message: "\(response.status)", confirmText: "OK")
                    }
                } else {
                    if let success = response.success {
                        if success {
                            self.performSegue(withIdentifier: "submitSuccess", sender: nil)
                        } else {
//                            print(response.data)
                            self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
                        }
                    }
                }
            })
            .addDisposableTo(disposeBag)
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func chooseBanquetHall(_ sender: UITapGestureRecognizer) {
        if !isBH { //只有从酒楼详情页面进来才能选择宴会厅
            for textfield in textFields {
                textfield.resignFirstResponder()
            }
            if let bhs = restaurant?.banquetHalls {
                if bhs.count > 0 {
                    self.performSegue(withIdentifier: "showPicker", sender: nil)
                } else {
                    self.showPromptView(message: LanguageHelper.getString(key: "NO_FEASTHALL"), confirmText: LanguageHelper.getString(key: "OK"))
                }
            }
        }
    }
    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showPicker" {
            let tempNav = segue.destination as! UINavigationController
            let tempPicker = tempNav.topViewController as! BanquetHallPickerViewController
            tempPicker.currentSelectedValue = chosenBH
            tempPicker.banquetHalls = (restaurant?.banquetHalls)!
            tempPicker.updateSelectedValue = { [unowned self] newSelectedValue in
                self.chosenBH = newSelectedValue
                self.banquetHallField.text = newSelectedValue.name
                self.banquetHallField.textColor = UIColor.gray
            }
        }
    }
 

}

extension BookingViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !notResign{
            for textfield in textFields {
                textfield.resignFirstResponder()
            }
            for tf in dateArea.textfields {
                tf.resignFirstResponder()
            }
        }
    }
}

extension BookingViewController: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        var newFrame = scrollView?.frame
        newFrame?.origin.y = (textField.superview?.frame.origin.y)!
        notResign = true
        scrollView?.scrollRectToVisible(newFrame!, animated: true)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [unowned self] in
            self.notResign = false
        }
    }
}

extension BookingViewController: DateAreaDelegate {
    func addDate(textfield: UITextField) {
        let newFrame = CGRect(x: dateArea.frame.origin.x, y: dateArea.frame.origin.y, width: dateArea.frame.width, height: dateArea.frame.height + menuHeight)
        dateArea.frame = newFrame
        scrollView?.contentSize = CGSize(width: self.view.bounds.width, height: dateArea.frame.origin.y + dateArea.frame.height)
        dateArea.layoutSubviews()
    }
    func deleteDate() {
        let newFrame = CGRect(x: dateArea.frame.origin.x, y: dateArea.frame.origin.y, width: dateArea.frame.width, height: dateArea.frame.height - menuHeight)
        dateArea.frame = newFrame
        scrollView?.contentSize = CGSize(width: self.view.bounds.width, height: dateArea.frame.origin.y + dateArea.frame.height)
        dateArea.layoutSubviews()
    }
    func maxDate() {
        self.showPromptView(message: LanguageHelper.getString(key: "NO_MORETHAN5DATE"), confirmText: LanguageHelper.getString(key: "OK"))
    }
    func pickADate(textfield: UITextField) {
        let view = CalendarViewController()
        view.afterPickDates = { beginDate, endDate in
            var text = beginDate
            if let end = endDate {
                text.append("-\(end)")
            }
            textfield.text = text
        }
        self.navigationController?.pushViewController(view, animated: true)
    }
    
    
}
